package cn.stylefeng.guns.core.common.page;

import cn.hutool.core.convert.Convert;
import cn.stylefeng.roses.core.util.HttpContext;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import javax.servlet.http.HttpServletRequest;

/**
 * Layui Table默认的分页参数创建
 */
public class LayuiPageFactory {

    /**
     * 获取layui table的分页参数
     */
    public static <T> Page<T> defaultPage() {
        HttpServletRequest request = HttpContext.getRequest();

        Integer pageNum = Convert.toInt(request.getParameter("page"), null);
        if (pageNum == null) {
            pageNum = Convert.toInt(request.getParameter("pageNum"), null);
        }

        Integer pageSize = Convert.toInt(request.getParameter("limit"), null);
        if (pageSize == null) {
            pageSize = Convert.toInt(request.getParameter("pageSize"), null);
        }


        if (pageSize == null) {
            pageSize = 10;
        }
        if (pageNum == null) {
            pageNum = 1;
        }


        return new Page<>(pageNum, pageSize);
    }

    /**
     * 创建layui能识别的分页响应参数
     */
    @SuppressWarnings("rawtypes")
    public static LayuiPageInfo createPageInfo(IPage page) {
        LayuiPageInfo result = new LayuiPageInfo();
        result.setCount(page.getTotal());
        result.setData(page.getRecords());
        return result;
    }
}
